package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"logistics-golang/dao"
	"logistics-golang/endpoint"
	"logistics-golang/service"
	"logistics-golang/transport"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"syscall"
)

func main() {

	var (
		// 服务地址和服务名
		servicePort = flag.Int("service.port", 10010, "service port")
	)

	flag.Parse()

	// 上下文根结点
	ctx := context.Background()
	// 异常通道，用于传递
	errChan := make(chan error)

	// 连接数据库，dao 获取连接
	err := dao.InitMysql("127.0.0.1", "3306", "root", "root", "logistics")
	if err != nil {
		log.Fatal(err)
	}

	// 获取用户服务（UserService）接口
	userService := service.MakeUserServiceImpl(&dao.UserDAOImpl{})

	// 定义用户服务 endpoint
	userEndpoints := &endpoint.UserEndpoints{
		RegisterEndpoint: endpoint.MakeRegisterEndpoint(userService),
		LoginEndpoint:    endpoint.MakeLoginEndpoint(userService),
	}

	// 创建 http handler
	r := transport.MakeHttpHandler(ctx, userEndpoints)

	// 启动 server 服务
	go func() {
		servicePortStr := strconv.Itoa(*servicePort)
		errChan <- http.ListenAndServe(":"+servicePortStr, r)
	}()

	// 监听退出
	go func() {
		// 监控系统信号，等待 ctrl + c 系统信号通知服务关闭
		c := make(chan os.Signal, 1)
		signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
		errChan <- fmt.Errorf("%s", <-c)
	}()

	// 打印异常
	error := <-errChan
	log.Println(error)

}
